using UnityEngine;
using QFramework;
using Unity.VisualScripting;
using UnityEngine.Serialization;
using Vector2 = UnityEngine.Vector2;

namespace Survivor
{
	public partial class SimpleAbility : ViewController
	{
		[SerializeField] private float _currentSeconds;
		private RaycastHit2D[] _attackResult;
		public LayerMask AttackTargetLayer;
		void Start()
		{
			// Code Here
			_currentSeconds = 0f;
			_attackResult = new RaycastHit2D[30];
		}

		private void Update()
		{
			_currentSeconds += Time.deltaTime;
			if (_currentSeconds >= Global.SimpleAttackInterval.Value)
			{

				var size = Physics2D.CircleCastNonAlloc(Player.Default.transform.position, 
					Global.SimpleAttackRange.Value, Vector2.zero,_attackResult,1,AttackTargetLayer);
				if (size ==0) return;
				_currentSeconds = 0f;
				size = Mathf.Min(size, Global.SimpleAttackCount.Value + Global.FlyThingCount.Value);
				for (int i = 0; i < size ; i++)
				{
					var enemy = _attackResult[i].collider.gameObject.GetComponentInParent<Enemy>();
					if (enemy)
					{
						// enemy.Hurt(Global.SimpleAttackDamage.Value);
						Sword.Instantiate().Show().Position(enemy.Position() + Vector3.left * 0.25f).Self((self) =>
						{
							var selfCache = self;
							var endRotation1 = new Vector3(0, 0, -10);
							var endRotation2 = new Vector3(0, 0, -120);
							ActionKit.Sequence()
								.Parallel((p) =>
								{
									p.Lerp(0, 1, 0.2f, (t) =>
									{
										selfCache.transform.rotation =
											Quaternion.Euler(Vector3.Slerp(Vector3.zero, endRotation1, t));
									});
									p.Append(ActionKit.Sequence()
										.Lerp(0, 1.25f, 0.1f, (scale) => selfCache.LocalScale(scale))
											.Lerp(1.25f, 1, 0.1f, (scale) => selfCache.LocalScale(scale)));
								}).Parallel((p) =>
								{
									p.Lerp(0, 1, 0.2f, (t) =>
									{
										selfCache.transform.rotation =
											Quaternion.Euler(Vector3.Slerp(Vector3.zero, endRotation2, t));
									});
								}).Callback(() =>
								{
									if (!enemy.IsDestroyed())
									{
										enemy.Hurt(Global.SimpleAttackDamage.Value);
									}
								})
								.Start(this, () =>
								{
									selfCache.DestroySelfGracefully();
								});
						});

					}
				}
			}
		}

		private void OnDrawGizmos()
		{
			Gizmos.color = Color.yellow;
			Gizmos.DrawWireSphere(gameObject.transform.position,Global.SimpleAttackRange.Value);
		}
	}
}
